<?php

namespace app\admin\controller;
use think\Loader;
use think\Config;
use app\common\model\Banner;
class LoginBannerController extends BaseController{
  public function _initialize(){
    parent::_initialize();
    $this->Model = new Banner();
    $this->type = "Login";
  }

  public function index(){
    $param = $this->request->param();
    if(empty($param)){
      $param = [];
    }
    $res = $this->Model->managerSelect(array_merge($param, ["type" => $this->type]));
    $this->assign("param", $param);
    $this->assign("res", $res);
    return $this->fetch();
  }

  public function create(){
    if($this->request->isPost()){
      $data = $this->getPostData();
      $res = $this->Model->createOrUpdate($data);
      if($res["status"]){
        $this->success($res["msg"], 'index');
      }else{
        $this->error($res["msg"]);
      }
    }else{
      $banner = ["status" => 1, "wap_cover_id" => 0, "start_time" => "", "end_time" => ""];
      $this->assign("banner", $banner);
      return $this->fetch("form");
    }
  }

  /**
   * 显示指定的资源
   *
   * @param  int  $id
   * @return \think\Response
   */
  public function read($id)
  {
    $banner = $this->Model->where("id", $id)->where("type", $this->type)->find();
    if(empty($banner)){
      $this->redirect('index');
    }
  }

  /**
   * 显示编辑资源表单页.
   *
   * @param  int  $id
   * @return \think\Response
   */
  public function edit($id){
    $banner = $this->Model->where("id", $id)->where("type", $this->type)->find();
    if(empty($banner)){
      $this->redirect('index');
    }

    if($this->request->isPost()){
      $data = $this->getPostData();
      $res = $this->Model->createOrUpdate($data);
      if($res["status"]){
        $this->success($res["msg"], 'index');
      }else{
        $this->error($res["msg"]);
      }
    }else{
      $this->assign("banner", $banner);
      return $this->fetch("form");
    }
  }

  /**
   * 删除指定资源
   *
   * @param  int  $id
   * @return \think\Response
   */
  public function delete($id){
    if($this->request->isDelete()){
      $id = $this->request->param("id");
      Banner::destroy($id);
      $this->success("删除成功", url("index"));  
    }else{
      $this->error("您请求的方法不存在", url("index"));
    }
  }

  private function getPostData(){
    $data = ["type" => $this->type, "status" => 0];
    $param_name = ["id", "wap_cover_id", "status", "title","start_time","end_time"];
    $param = $this->request->post();
    foreach ($param_name as $key) {
      if(isset($param[$key])){
        $val = $param[$key];
      }else{
        $val = "";
      }

      if($key == "id" && empty($val)){
        continue;
      }

      switch ($key) {
      case "status":
      case "wap_cover_id":
        $val = intval($val);
        break;
      case "start_time":
      case "end_time":
        $val = strtotime($val);
        break;
      default:
        $val = trim($val);  
      }
      $data[$key] = $val;
    }
    return $data;
  }
}
